<template>
  <div class="home" v-if="isshow">
    <vueCropper
      style="width: 100%; height: 100vh"
      ref="cropper"
      :img="img"
      :autoCrop="option.autoCrop"
      :centerBox="option.centerBox"
      :fixedNumber="option.fixedNumber"
      :infoTrue="option.infoTrue"
      :fixed="option.fixed"
    ></vueCropper>
    <div class="footer-box">
      <div class="button" @click="clear">取消</div>
      <div class="button" @click="save">保存</div>
    </div>
  </div>
</template>
<script>
export default {
  name: "cutimg",
  props: {
    img: {
      //图片地址
      type: String,
      default: "",
    },
    isshow: {
      //是否显示
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      option: {
        fixed: false, //开启截图框宽高固定比例
        fixedNumber: [1, 1], //截图框的宽高比例
        autoCrop: true, //默认生成截图框
        centerBox: true, //截图框是否被限制在图片里面
      },
    };
  },
  mounted() {},
  methods: {
    //保存
    save() {
      // 获取截图的File对象
      this.$refs.cropper.getCropData((data) => {
        //base64 转 file对象
        const file = this.base64ToFile(data, "fileName");
        //生成图片显示的对象 父组件要用
        let obj = {
          content: data,
          file: file,
          message: "",
          status: "",
        };
        //向父组件传参
        this.$emit("getimgurl", obj);
      });
    },
    //base64 转 file对象
    base64ToFile(base64, fileName) {
      let arr = base64.split(","),
        type = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], fileName, { type });
    },
    //关闭弹窗 调用父组件的方法
    clear() {
      this.$emit("clear");
    },
  },
};
</script>
<style scoped>
.home {
  position: fixed;
  width: 100%;
  height: 100vh;
  left: 0;
  top: 0;
  z-index: 99;
}
.footer-box {
  position: fixed;
  width: 100%;
  left: 0;
  bottom: 0;
  display: flex;
  padding: 15px 0;
}
.button {
  flex: 1;
  text-align: center;
  color: #ffffff;
  font-size: 18px;
  font-weight: bold;
}
</style>